<?php

function list_insentif(){
	my_set_code_js('
		function confirmDelete(id){
			var t = confirm(\'Yakin akan menghapus data ?\');
			if(t){
				location.href=\'index.php?com='.$_GET['com'].'&task=delete&id=\'+id;
			}
			return false;
		}
	');

	$header = array(
		'Tahun'=>array('style'=>'border-bottom:2px solid;width:20%'),  
		'Bulan'=>array('style'=>'text-align:left;border-bottom:2px solid;width:10%'),   
		'Total Dana'=>array('style'=>'text-align:right;border-bottom:2px solid;width:30%'),   
		'Distribusi'=>array('style'=>'text-align:right;border-bottom:2px solid;width:20%'),   
		'Proses'=>array('style'=>'text-align:center;border-bottom:2px solid;width:10%'),   
		' '=>array('style'=>'border-bottom:2px solid;width:10%'), 
	);
	$periode_id =get_periode_gaji();
	$periode = my_get_data_by_id('pr_periode','periode_id',$periode_id);
	$tanggal = $periode['tanggal'];

	$query = "SELECT * FROM pr_insentif 
		ORDER BY insentif_id DESC";
	$result = my_query($query );
	$total_records = my_num_rows($result );
	$scroll_page =5;  
	$per_page =25;  
	$current_page = isset($_GET['page']) ? (int) $_GET['page'] : 1 ; 
	if($current_page < 1){
		$current_page = 1;
	}		 
	$pager_url  ="index.php?com={$_GET['com']}&task={$_GET['task']}&field={$_GET['field']}&key={$_GET['key']}&page=";	 
	$inactive_page_tag = 'style="padding:4px;background-color:#BBBBBB"';  
	$previous_page_text = ' Mundur '; 
	$next_page_text = ' Maju ';  
	$first_page_text = ' Awal '; 
	$last_page_text = ' Akhir ';
	
	$kgPagerOBJ = new kgPager();
	$kgPagerOBJ->pager_set(
		$pager_url, 
		$total_records, 
		$scroll_page, 
		$per_page, 
		$current_page, 
		$inactive_page_tag, 
		$previous_page_text, 
		$next_page_text, 
		$first_page_text, 
		$last_page_text ,$pager_url_last); 
	 		
	$result = my_query($query ." LIMIT ".$kgPagerOBJ->start.", ".$kgPagerOBJ->per_page); 	
	$row = array(); 
	$i = ($current_page  - 1 ) * 25; 
	while( $ey =my_fetch_array($result) ){
		$detailproperty = array(
				'href'=>'index.php?com='.$_GET['com'].'&task=detail&id='.$ey['insentif_id'],
				'title'=>'Detail periode'
		);
		$detail_button = button_icon( 'b_props.png' , $detailproperty  );

		if($ey['tanggal']>=$tanggal){
			$editproperty = array(
					'href'=>'index.php?com='.$_GET['com'].'&task=edit&id='.$ey['insentif_id'],
					'rel'=>'facebox',
					'title'=>'Edit'
			);
			$edit_button = button_icon( 'b_edit.png' , $editproperty  );
			
			$deleteproperty = array(
					'href'=>'javascript:; ',
					'onclick'=>'javascript:confirmDelete('.$ey['insentif_id'].');',
					'title'=>'Delete'
				);
			$delete_button = button_icon( 'b_drop.png' , $deleteproperty  );
		}else{
			$edit_button = button_icon( 'b_edit_off.png' , '' );
			$delete_button = button_icon( 'b_drop_off.png' , ''  );
		}

		$row[] = array(
			'tahun'=>date('Y',strtotime($ey['tanggal'])),
			'bulan'=>date('m',strtotime($ey['tanggal'])),
			'dana'=>position_text_align(rp_format($ey['total_dana']),'right'),
			'dist'=>position_text_align($ey['distribusi'].' %','right'),
			'proses'=>position_text_align($ey['proses'],'center'),
			' v'=>position_text_align($edit_button.' '.$detail_button.' '.$delete_button,'right'),
		);
	}
	$datas = table_rows($row);
	$view  ='<table width="100%"   style="border-collapse:collapse;border-color:white" cellspacing="0" cellpadding="2">';
	$temp=(int) date('m' , strtotime($tanggal));
	$view .= form_field_display( '<span class="label_form"> '.sprintf( '%02d',$temp).'-'.date('Y' , strtotime($tanggal)).'</span>'   , "<b>Periode Gaji</b>"    ); 
	$menuontop = array(  
		'Tambah data'=>array('onclick'=>'javascript: jQuery.facebox({ ajax: \'index.php?com=pr_insentif&task=edit\' });'),
	);
	$printmenu = additional_menu_on_list( $menuontop , '');
	$paging = $kgPagerOBJ ->showPaging();
	return $view.$printmenu .table_builder($header , $datas ,  6 , false , $paging);
}

function form_insentif( $id ){
	my_set_file_js(
		array(
			'components/system/jquery/combomulti/jquery.chainedSelects.js',
			'components/system/js/calendar/calendarDateInput.js' 
		)
	);

	$view = form_header( "seleski" , "seleski"  );
	if($id>0){
		$fields = my_get_data_by_id('pr_insentif','insentif_id',$id);
		$month = date('m',strtotime($fields['tanggal']));
		$year = date('Y',strtotime($fields['tanggal']));	
	}else{
		$month = date('m');
		$year = date('Y');
	} 

	$bulans  = array(
		'01'=>'01', 
		'02'=>'02', 
		'03'=>'03', 
		'04'=>'04', 
		'05'=>'05', 
		'06'=>'06', 
		'07'=>'07', 
		'08'=>'08', 
		'09'=>'09', 
		'10'=>'10', 
		'11'=>'11', 
		'12'=>'12', 
	);
	$bulan = array(
		'name'=>'bulan',
		'value'=>isset($_POST['bulan']) ? $_POST['bulan']: $month  
	);
	$bulan_form = form_dropdown( $bulan,$bulans);
	
	$tahun = array(
		'name'=>'tahun','size'=>5,
		'value'=>isset($_POST['tahun']) ? $_POST['tahun']: $year
	); 
	$tahun_form = form_dynamic($tahun );
	$view .= form_field_display( $bulan_form.' '. $tahun_form  , "Periode"    );

	$total_dana = array(
				'name'=>'total_dana',
				'value'=>( isset($_POST['total_dana']) ? $_POST['total_dana'] : rp_format($fields['total_dana']) ),
				'id'=>'total_dana',
				'type'=>'text',
				'size'=>'20'
			);
	$form_field_total = form_money($total_dana); 
	$view .= form_field_display( $form_field_total   , "Total Dana"   );

	$distribusi = array(
				'name'=>'distribusi',
				'value'=>( isset($_POST['distribusi']) ? $_POST['distribusi'] : $fields['distribusi'] ),
				'id'=>'distribusi',
				'type'=>'text',
				'size'=>'5'
			);
	$form_field_distribusi = form_dynamic($distribusi); 
	$view .= form_field_display( $form_field_distribusi.' %'   , "Distribusi"   );
	
	$submit = array(
		'value' => ( $id ==0 ? ' Simpan ' :'  Update  '),
		'name' => 'simpan', 
		'type'=>'submit','class'=>'main_button'
	);
	$form_submit= form_dynamic($submit); 
	
	$view .= form_field_display( $form_submit  , "&nbsp;" ,  "" );
	$view .= form_footer( );
	return $view;
}

function insentif_validate($id){
	$errsubmit = false;
	$err = array();

	if( $errsubmit){
		return $err;
	}
	return $errsubmit;
}

function submit_insentif($id = 0){
	$tanggal = $_POST['tahun'].'-'.$_POST['bulan'].'-01';
	$datas = array(
		'tanggal'=> my_type_data_str($tanggal),	
		'total_dana'=>my_type_data_str(set_text_as_number($_POST['total_dana'])),
		'distribusi'=> my_type_data_int($_POST['distribusi']),
		'proses'=> my_type_data_str('T'),
	);
	if($id > 0){
		 return my_update_record( 'pr_insentif' , 'insentif_id' , $id , $datas);
	}
	return my_insert_record( 'pr_insentif' , $datas );
}
 
function delete_insentif($id){
	$query = "DELETE FROM pr_insentif WHERE insentif_id ={$id} ";
	return my_query($query);
}	

function list_karyawan($id){
	$header = array(
		'#'=>array('style'=>'border-bottom:2px solid;width:5%'),  
		'NIK'=>array('style'=>'border-bottom:2px solid;width:10%'),  
		'Nama Karyawan'=>array('style'=>'border-bottom:2px solid;width:30%'),  
		'Nipar'=>array('style'=>'border-bottom:2px solid;width:10%'),   
		'N.H'=>array('style'=>'border-bottom:2px solid;width:10%'),   
		'Pot. Tatib'=>array('style'=>'text-align:right;border-bottom:2px solid;width:10%'),   
		'Insentif'=>array('style'=>'text-align:right;border-bottom:2px solid;width:25%'),   
	);
	if(isset($_GET['key'])){
		$query = "
			SELECT * FROM pr_insentif_karyawan a
			INNER JOIN karyawan b ON a.karyawan_id=b.karyawan_id 
			INNER JOIN biodata c ON c.biodata_id=b.biodata_id 
			WHERE a.insentif_id={$id} 
			AND ( c.nama LIKE '%{$_GET['key']}%' OR b.nik ='{$_GET['key']}' )
			ORDER BY b.nik 
		";
	}else{
		$query = "
			SELECT * FROM pr_insentif_karyawan a
			INNER JOIN karyawan b ON a.karyawan_id=b.karyawan_id 
			WHERE a.insentif_id={$id} ORDER BY b.nik 
		";
	}

	$pr_insentif = my_get_data_by_id('pr_insentif','insentif_id',$id);
	
	$result = my_query($query );
	$total_records = my_num_rows($result );
	$scroll_page =5;  
	$per_page =25;  
	$current_page = isset($_GET['page']) ? (int) $_GET['page'] : 1 ; 
	if($current_page < 1){
		$current_page = 1;
	}		 
	$pager_url  ="index.php?com={$_GET['com']}&task={$_GET['task']}&id={$_GET['id']}&key={$_GET['key']}&page=";	 
	$inactive_page_tag = 'style="padding:4px;background-color:#BBBBBB"';  
	$previous_page_text = ' Mundur '; 
	$next_page_text = ' Maju ';  
	$first_page_text = ' Awal '; 
	$last_page_text = ' Akhir ';
	
	$kgPagerOBJ = new kgPager();
	$kgPagerOBJ->pager_set(
		$pager_url, 
		$total_records, 
		$scroll_page, 
		$per_page, 
		$current_page, 
		$inactive_page_tag, 
		$previous_page_text, 
		$next_page_text, 
		$first_page_text, 
		$last_page_text ,$pager_url_last); 
	 		
	$result = my_query($query ." LIMIT ".$kgPagerOBJ->start.", ".$kgPagerOBJ->per_page); 	
	$row = array(); 
	$i = ($current_page  - 1 ) * 25;  
	while($ey = my_fetch_array($result)){
		$i++;
		$karyawan = loaddata_karyawan($ey['karyawan_id']); 
		$jabatan = loaddata_jabatan($karyawan['jabatan_id']); 
		$pot=get_tatib_pot_insentif($pr_insentif['tanggal'] , $ey['karyawan_id']  );
		if((int) $pot <>0 ){
			$pot.=' %' ;
		}
 		$row[] = array(
			'#'=>position_text_align ($i, 'center'), 
			'nik'=>  $karyawan['nik'] ,   
			'nama'=>  $karyawan['nama_gelar'] ,   
			'nipar'=> $ey['nipar_a']  ,   
			'nh'=> $ey['nipar_h']  ,   
			'pot'=> position_text_align ($pot, 'right'), 
			'insentif'=> position_text_align (rp_format($ey['nominal']),'right')  ,   
		);
	}
	$datas = table_rows($row);   
	$search = '<form method="GET">
	<input type="hidden" name="com" value="'.$_GET['com'].'" />
	<input type="hidden" name="task" value="'.$_GET['task'].'" />
	<input type="hidden" name="id" value="'.$_GET['id'].'" />
	<span style="font:10px verdana"><b>Pencarian cepat</b></span><br/><input type="text"  style="width:200px;" name="key" value="'.(isset($_GET['key']) ? $_GET['key']: "").'" /><input class="simple_search" type="submit" value=" CARI " /> </form>';
	$view ='<table width="98%" cellspacing="0" cellpadding="4"><tr>'; 
	$view .= '<table width="100%"   style="border-collapse:collapse;border-color:white" cellspacing="0" cellpadding="2">
';
	$view .= '<tr><td>'.$search .'</td><td valign="bottom"><div style="width:100%;text-align:right;"></div></td></tr>'   ; 
	$view .= form_field_display( '<span class="label_form">'.  date( "m-Y" , strtotime($pr_insentif['tanggal'])) .'</span>'   , "<b>Periode</b>"    ); 
	$view .= form_field_display( '<span class="label_form">'.  'Rp. '.rp_format($pr_insentif['total_dana']).'</span>'   , "<b>Total Dana</b>"    ); 
	$view .= form_field_display( '<span class="label_form">'.  $pr_insentif['distribusi'].' %' .'</span>'   , "<b>Distribusi</b>"    ); 
	$view .= '</table>';
	$view .= '</td></tr></table><br/>';
	$menuontop = array(  
		($pr_insentif['proses']=="Y" ? 'Reproses' : 'Proses') => array('onclick'=>'javascript: jQuery.facebox({ ajax: \'index.php?com=pr_insentif&task=loadpage&id='.$id.'\' });'),
		'Cetak' => array('onclick'=>'javascript:window.open(\'index.php?com='.$_GET['com'].'&task=plaincetak&id='.$id.'&key='.$_GET['key'].'\',\'mywin\',\'left=20,top=20,width=800,height=600,toolbar=0,scrollbars,resizable=0\');'),
		'Excel'=>array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'&task=excel&id='.$id.'&key='.$_GET['key'].'\';'),
		'Kembali'=>array('onclick'=>'javascript:location.href=\'index.php?com='.$_GET['com'].'\';'),
	);	
	$printmenu = additional_menu_on_list( $menuontop ,'' ); 
	$paging = $kgPagerOBJ ->showPaging();
	return  $view .$printmenu. table_builder($header , $datas , 4, false ,$paging);
}

function update_insentif_karyawan($id){
	ini_set("max_execution_time","10000");	
	$t = write_data_a_absen_payroll();
 
	$query = "DELETE FROM pr_insentif_karyawan WHERE insentif_id={$id}";
	my_query($query);
	$insentifs=my_get_data_by_id('pr_insentif','insentif_id',$id) ;
	$tanggal=$insentifs['tanggal'] ;
	$bulan = (int) date('m' , strtotime($tanggal));
	$tahun = (int) date('Y' , strtotime($tanggal));
	if($bulan<=3){
		$bulan_kontrak=12+$bulan-3 ;
		$tahun_kontrak=$tahun-1 ;
	}else{	
		$bulan_kontrak=$bulan-3 ;
		$tahun_kontrak=$tahun ;
	}
	$tgl_kontrak=$tahun_kontrak.'-'.sprintf( '%02d',$bulan_kontrak) .'-01';	
	if($bulan =='01' ){
		$bulan = '12';
		$tahun-- ;	
	}else{
		$bulan-- ;
	}			
//	$tgl=$tahun.'-'.sprintf( '%02d',$bulan) .'-01';
	$tgl=$tahun.'-'.sprintf( '%02d',$bulan) .'-11';
	$query = "
		SELECT * FROM karyawan a 
		INNER JOIN kekaryawanan b ON b.karyawan_id=a.karyawan_id 
		WHERE a.karyawan_id NOT IN (select karyawan_id FROM karyawan_disable)
		AND a.karyawan_id NOT IN 
		(select karyawan_id FROM pemberhentian 
		where TMT<'".$tgl."') 
		AND b.status_insentif='paid'" ;
		 
	$result = my_query($query);
	$i =$tot_nipar_h= 0;
	$total_nipar_h=kalkulasi_nipar_h($id,$tanggal);
	$pr_insentif = my_get_data_by_id('pr_insentif','insentif_id',$id);
	$total_dana=$pr_insentif['total_dana']*$pr_insentif['distribusi']/100 ;

	while($ey = my_fetch_array($result)){
		$karyawan = loaddata_karyawan($ey['karyawan_id']); 
		$jabatan = loaddata_jabatan($karyawan['jabatan_id']);
		$golongan_jabatan_id=isset( $karyawan['golongan_jabatan_id'] ) ? $karyawan['golongan_jabatan_id']:  0;
		$nipars=my_get_data_by_id('nipar','golongan_jabatan_id',$golongan_jabatan_id );
	
		if($jabatan['sumber_pendukung']=='Sumber'){
			$nipar=$nipars['sumber'] ;
		}elseif($jabatan['sumber_pendukung']=='Pendukung'){	
			$nipar=$nipars['pendukung'] ;
		}else{
			$nipar=0 ;
		}
	
		if($nipar>0){
			$potongans=get_potongan($ey['karyawan_id'],$tanggal);	 			
			
			$tot_pot=$potongans['hari']*8+$potongans['jam']+$potongans['menit']/60 ;
			
			if($tot_pot<0){
				$nipar_h=0;
			}elseif($tot_pot>173){
				$nipar_h=0;
			}else{
				//if($karyawan['tmb']>=$tanggal){
				//	$nipar_h=0;
				//}else{
					$nipar_h=$nipar-($nipar*$tot_pot/173) ;
					if($karyawan['status_kekaryawan_id']==2){  //kontrak
						if($karyawan['tmb']>=$tgl_kontrak){
							$nipar_h=$nipar_h*0.5 ;
						}
					}
					$nipar_h=round($nipar_h,2);
				//}	
				
			}			
			
			if($total_nipar_h==0){
				$nominal=0;
			}else{	
				$nominal=round($total_dana*$nipar_h/$total_nipar_h,0);
			}	
			$datas = array(
				'insentif_id'=>my_type_data_int($id),
				'karyawan_id'=>my_type_data_int($ey['karyawan_id']),
				'nipar_a'=>my_type_data_int($nipar)  ,   
				'nipar_h'=>my_type_data_str($nipar_h),
				'pot_hari'=>my_type_data_int($potongans['hari']),
				'pot_jam'=>my_type_data_int($potongans['jam']),
				'pot_menit'=>my_type_data_int($potongans['menit']),
				'nominal'=>my_type_data_str( $nominal ),
			);
			my_insert_record('pr_insentif_karyawan',$datas);
		}	
	}

	$total_nipar = get_total_nipar($id);
	
	$result = my_query($query);
	while($ey2 = my_fetch_array($result)){
		$nipar_karyawan = get_nipar_karyawan($ey2['karyawan_id'] , $id);
		$newnom = $total_dana *( $nipar_karyawan /$total_nipar );
		$quesry = "UPDATE pr_insentif_karyawan SET nominal = '{$newnom}' WHERE karyawan_id = {$ey2['karyawan_id']} AND insentif_id = {$id} LIMIT 1";
		my_query($quesry);
	}

	$datas = array(
		'proses'=> my_type_data_str('Y'),
	);
	return my_update_record( 'pr_insentif' , 'insentif_id' , $id , $datas);
}


function get_nipar_karyawan($karyawan_id , $insentif_id){
	$query = "SELECT  nipar_h  FROM pr_insentif_karyawan WHERE karyawan_id = {$karyawan_id} AND insentif_id = {$insentif_id}";
	$res = my_query($query);
	$row = my_fetch_array($res);
	return $row['nipar_h'];
}

function get_total_nipar($insentif_id){
	$query = "SELECT SUM(nipar_h) as tot FROM pr_insentif_karyawan WHERE insentif_id = {$insentif_id}";
	$res = my_query($query);
	$row = my_fetch_array($res);
	return $row['tot'];
}

function kalkulasi_nipar_h($id=0,$tanggal){
	$bulan = (int) date('m' , strtotime($tanggal));
	$tahun = (int) date('Y' , strtotime($tanggal));
	if($bulan<=3){
		$bulan_kontrak=12+$bulan-3 ;
		$tahun_kontrak=$tahun-1 ;
	}else{	
		$bulan_kontrak=$bulan-3 ;
		$tahun_kontrak=$tahun ;
	}
	$tgl_kontrak=$tahun_kontrak.'-'.sprintf( '%02d',$bulan_kontrak) .'-01';
	
	if($bulan =='01' ){
		$bulan = '12';
		$tahun-- ;	
	}else{
		$bulan-- ;
	}			
//	$tgl=$tahun.'-'.sprintf( '%02d',$bulan) .'-01';
	$tgl=$tahun.'-'.sprintf( '%02d',$bulan) .'-11';
	$periode_id =get_periode_gaji();
	$query = "
		SELECT * FROM karyawan a 
		INNER JOIN a_absen_payroll b ON b.karyawan_id=a.karyawan_id 
		INNER JOIN kekaryawanan c ON c.karyawan_id=a.karyawan_id 
		AND b.periode_id=".$periode_id." 
		WHERE a.karyawan_id NOT IN (select karyawan_id FROM karyawan_disable)
		AND a.karyawan_id NOT IN 
		(select karyawan_id FROM pemberhentian 
		where TMT<'".$tgl."') 
		AND c.status_insentif='paid'" ;
		 
	$result = my_query($query);
	$tot_nipar_h= 0;
	while($ey = my_fetch_array($result)){
		$karyawan = loaddata_karyawan($ey['karyawan_id']); 
		$jabatan = loaddata_jabatan($karyawan['jabatan_id']); 
		$golongan_jabatan_id=isset( $karyawan['golongan_jabatan_id'] ) ? $karyawan['golongan_jabatan_id']:  0;
		$nipars=my_get_data_by_id('nipar','golongan_jabatan_id',$golongan_jabatan_id );
		if($jabatan['sumber_pendukung']=='Sumber'){
			$nipar=$nipars['sumber'] ;
		}else{
			$nipar=$nipars['pendukung'] ;
		}
		
		$tot_pot=$ey['insentif_pot_hari_1_31']*8
				+$ey['insentif_pot_jam_1_31']
				+$ey['insentif_pot_menit_1_31']/60 ;
		
		 
		if($tot_pot<0){
			$nipar_h=0;
		}elseif($tot_pot>173){
			$nipar_h=0;
		}else{
			if($karyawan['tmb']>=$tanggal){
				$nipar_h=0;
			}else{
				$nipar_h=$nipar-($nipar*$tot_pot/173) ;
				if($karyawan['status_kekaryawan_id']==2){  //kontrak
					if($karyawan['tmb']>=$tgl_kontrak){
						$nipar_h=$nipar_h*0.5 ;
					}			
				}
			}	
			$tot_nipar_h+=$nipar_h ;
		}
	}
	return $tot_nipar_h ;
}
	
function get_potongan($karyawan_id,$tanggal){
	$periode_id=get_periode_gaji() ;

	$bulan = date('m',strtotime($tanggal));
	$tahun = date('Y',strtotime($tanggal));	
	$query = "
		SELECT * FROM a_absen_payroll	
		WHERE periode_id={$periode_id} 
		AND karyawan_id={$karyawan_id}"
	;
	if( (int) $karyawan_id == 77){print($query);}
	$result = my_query($query); 	
	$insentifs =my_fetch_array($result) ;
	$pots=array();
	$pots['hari']=$insentifs['insentif_pot_hari_1_31'];
	$pots['jam']=$insentifs['insentif_pot_jam_1_31'];
	$pots['menit']=$insentifs['insentif_pot_menit_1_31'];
	return $pots ;
}



//WAKTU PAYROLL
function write_data_a_absen_payroll(){
	
	$periode_id =get_periode_gaji();
	$query = "DELETE FROM a_absen_payroll WHERE periode_id ={$periode_id} ";
	my_query($query);
	$end=get_batas_tmt() ;
	$i=0;
	$query = " SELECT a.karyawan_id FROM karyawan a
			INNER JOIN kekaryawanan b ON b.karyawan_id = a.karyawan_id 
			WHERE b.tmb  <= '{$end}' 
			AND a.karyawan_id NOT IN (select karyawan_id FROM karyawan_disable)
			AND a.karyawan_id NOT IN (select karyawan_id FROM pemberhentian  WHERE tmt <= '{$end}') 	
		";	
	$result = my_query($query);	
 	while($ey = my_fetch_array($result)){ 
		update_a_absen_payroll_each_karyawan($ey['karyawan_id'] , $periode_id);
		$i++;
	}
	return $i;
}

function get_periode_lalu(){
	$query = "SELECT MAX(periode_id) as mx FROM tmn_hari_kerja LIMIT 1";
	$res = my_query($query);
	$row = my_fetch_array($res);
	return $row['mx'];
}

function get_total_hadir_current($karyawan_id ){
	 
	$query = "SELECT COUNT(*) as tot FROM temp_tmn_hari 
		WHERE  ( 
			status_absen ='N' 
			OR  status_absen ='1' OR status_absen ='2' OR status_absen ='3' 
			OR  status_absen ='4' OR status_absen ='5' OR status_absen ='6' 
			OR  status_absen ='7' OR status_absen ='8' OR status_absen ='9' 
		) 
		AND karyawan_id = {$karyawan_id} AND tgl_index <= 10 " ;
	$res = my_query($query);
	$row = my_fetch_array($res);
	return $row['tot'];
}

function get_total_hadir_prev($karyawan_id,$periode_max_id){ 
	$query = "SELECT save_hari_prev_um tot FROM tmn_hari_kerja WHERE   karyawan_id = {$karyawan_id} ";
	$res = my_query($query);
	$row = my_fetch_array($res);
	return $row['tot'];
}

function get_total_khk($karyawan_id , $periode_max_id){
	$query = "SELECT  nhari FROM temp_tmn_khk WHERE karyawan_id = {$karyawan_id} "; 
	$res = my_query($query);
	$row = my_fetch_array($res); 
	return $row['nhari'];
}

function get_data_lembur( $karyawan_id , $limitlembur){
	 
	$query = "SELECT SUM(hour) as tot FROM temp_tmn_overtime WHERE karyawan_id = {$karyawan_id} AND hour >= '{$limitlembur}' ";
	$res = my_query($query);
	$row = my_fetch_array($res);
	return $row['nhari'];
}

function potong_insentif($karyawan_id , $periode_id ){
 
	$query = "SELECT DISTINCT  tgl_index  FROM temp_tmn_hari 
		WHERE  ( 
			status_absen ='C' 
			OR  status_absen ='BL' OR status_absen ='BP' OR status_absen ='HP' 
			OR  status_absen ='SW' OR status_absen ='SD' OR status_absen ='PP' 
			OR  status_absen ='UP' OR status_absen ='A' OR status_absen ='WP' 
		) 
		AND karyawan_id = {$karyawan_id}   AND tgl_index > 10" ;
	$res = my_query($query);
	$datas = my_num_rows($res);

	//$spd_berobat = get_spd_potong_insentif($karyawan_id , $periode_id);
 

	return   $datas ;//+ $spd_berobat;
}

function get_spd_potong_insentif($karyawan_id , $periode_id){
	$periode = my_get_data_by_id( 'pr_periode' ,'periode_id' , $periode_id );
	$tanggal = $periode['dari'];

	$lis = date('Y-m-',strtotime($tanggal));
	$start =  $lis.'01';
	$end = $lis.'31';
	$dates = list_kalender($start , $end );
 
	$i =0;
 
	foreach($dates as $date){
		$query = "SELECT * FROM spd_simple 
					WHERE  (  `status` <> 'A/J Pasien' OR `antar_pasien` = 'No'  )
				AND karyawan_id = {$karyawan_id} AND 
				(
						DATE( tanggal_mulai ) <= DATE(  '{$date}' ) 
					AND DATE( tanggal_akhir ) >= DATE(  '{$date}' )
				)  ";
		$result = my_query($query);
		if(my_num_rows($result) > 0){
			$i++;
		}
	} 
	return $i;
}
 
	
 

function update_a_absen_payroll_each_karyawan($karyawan_id , $periode_id){
 
	$periode_max_id = get_periode_lalu();
	$waktu_akhir = get_total_hadir_current($karyawan_id  );	 
	$waktu_awal = get_total_hadir_prev($karyawan_id,$periode_max_id);	

	$lembur_otomatis = get_total_khk($karyawan_id ,$periode_max_id);
 
	$lembur_jumlah_jam = get_data_lembur( $karyawan_id , 0);

	$lembur_lebih4jam = get_data_lembur( $karyawan_id , 4);
	
	$insentif_pot_hari_1_31 = potong_insentif( $karyawan_id ,$periode_max_id ); 
 	$potongan_menit = potong_insentif_menit($karyawan_id);
	
	$pot_transport = potongan_transport($karyawan_id);
	$datas = array(
		'karyawan_id'		=>my_type_data_int($karyawan_id),
		'periode_id'		=>my_type_data_int($periode_id),
		'hari_kerja_11_10'	=>my_type_data_str($waktu_akhir),
		'hari_kerja_1_31' 	=>my_type_data_str($waktu_awal),
		'lembur_otomatis' 	=>my_type_data_str($lembur_otomatis),
		'lembur_jumlah_jam' =>my_type_data_str($lembur_jumlah_jam),
		'lembur_lebih4jam'	=>my_type_data_str($lembur_lebih4jam),
		 
		'insentif_pot_hari_1_31'	=>my_type_data_str($insentif_pot_hari_1_31),
		'insentif_pot_jam_1_31'		=>my_type_data_str(0),
		'insentif_pot_menit_1_31'	=>my_type_data_str($potongan_menit),
		'lembur_56jam'=>my_type_data_str(0),
		'lembur_lebih56jam'=>my_type_data_str(0),
		'potong_absen_jam'=>my_type_data_str(0),
		'hourpay'=>my_type_data_str(0),
		'hourpay_56'=>my_type_data_str(0),
		'potong_transport'=>my_type_data_str($pot_transport),
		'kelompok_shift_id'=>my_type_data_str(0),
	); 
	return my_insert_record('a_absen_payroll' , $datas);
}

function potongan_transport($karyawan_id){
	$query = "SELECT COUNT(*) as tot FROM temp_tmn_hari 
		WHERE  (   status_absen ='HP' OR  status_absen ='SW'  
			OR  status_absen ='UP' OR status_absen ='A'  
		) 
		AND karyawan_id = {$karyawan_id} " ;
	$res = my_query($query);
	$row = my_fetch_array($res);
	return $row['tot'];
}


function potong_insentif_menit($karyawan_id){
	$query = "SELECT nmenit FROM temp_tmn_absensi WHERE karyawan_id = {$karyawan_id}";
	$res = my_query($query);
	if( my_num_rows($res) > 0 ){
		$row = my_fetch_array($res);
		return (-1) * $row['nmenit'];
	}
	return 0;
}

//END


function page_kalkulasi_insentif(){
	my_set_code_js('
	$(document).ready(function() {
       	$(\'#onebar\').load(\'index.php?com='.$_GET['com'].'&task=proses&id='.$_GET['id'].'&'.rand(0,9).'='.rand(0,99999).'\'); 
	});
	');
	return '<div id="onebar" style="width:100%;text-align:center;"><img src="components/system/jquery/facebox/loading.gif" /><br/>On processing!!!</div>';
}
	
	/*
do case
              case nTtl_Pot < 0
                   INC->NIPAR_H := 0
              case nTtl_Pot > 173
                   INC->NIPAR_H := 0
              otherW
                   if IPMAS->( dbseek( INC->NIK ) )
                      if IPMAS->HIRE >= ctod( '01/'+DANA->BULAN+'/'+DANA->TAHUN )
                         INC->NIPAR_H := 0
                      else
                         if IPMAS->STATUS #'1'
                            if IPMAS->HIRE >= ctod( '01/'+alltrim(str(if(val(DANA->BULAN)-3<=0,12+val(DANA->BULAN)-3,val(DANA->BULAN)-3)))+'/'+alltrim(str(if(val(DANA->BULAN)-3<=0,val(DANA->TAHUN)-1,val(DANA->TAHUN)))))
                               // 50%
                               INC->NIPAR_H := ( INC->NIPAR_A - ( if( nTtl_Pot > 0 ,( nTtl_POT / 173 ), 0 ) * INC->NIPAR_A ) ) * .5
                            else
                               // 100%
                               INC->NIPAR_H := INC->NIPAR_A - ( if( nTtl_Pot > 0 ,( nTtl_POT / 173 ), 0 ) * INC->NIPAR_A )
                            endif
                         else
                            // 100%
                            INC->NIPAR_H := INC->NIPAR_A - ( if( nTtl_Pot > 0 ,( nTtl_POT / 173 ), 0 ) * INC->NIPAR_A )
                         endif
                      endif
                   endif

           endcase
		   
	*/

	

function get_tatib_pot_insentif($periode , $karyawan_id ){

	list($yyyy,$mm,$dd) = explode("-" , $periode);
	$date_from=$yyyy.'-'.sprintf( '%02d',$mm) .'-01';
	$date_to=get_last_date_by_month( $yyyy, $mm);
	$query = "SELECT max(c.potongan_insentif)  as pot
		FROM tatib_detail a
		INNER JOIN tatib b ON b.tatib_id=a.tatib_id
		INNER JOIN jenis_peringatan c ON c.jenis_peringatan_id=a.jenis_peringatan_id 
		WHERE a.karyawan_id={$karyawan_id} 
		AND (b.tanggal BETWEEN '{$date_from}' AND '{$date_to}' )		
		ORDER BY b.tanggal";		
	$result = my_query($query);
	$re = my_fetch_array($result);
	return $re['pot'];
}	


function excel_report($id){
	my_component_load('xl_builder' , false);

	$header = array(
		'#'=>array('style'=>'border-bottom:2px solid;width:5%'),  
		'NIK'=>array('style'=>'border-bottom:2px solid;width:10%'),  
		'Nama Karyawan'=>array('style'=>'border-bottom:2px solid;width:30%'),  
		'Nipar'=>array('style'=>'border-bottom:2px solid;width:10%'),   
		'N.H'=>array('style'=>'border-bottom:2px solid;width:10%'),   
		'Pot. Tatib'=>array('style'=>'text-align:right;border-bottom:2px solid;width:10%'),   
		'Insentif'=>array('style'=>'text-align:right;border-bottom:2px solid;width:25%'),   
	);
	if(isset($_GET['key'])){
		$query = "
			SELECT * FROM pr_insentif_karyawan a
			INNER JOIN karyawan b ON a.karyawan_id=b.karyawan_id 
			INNER JOIN biodata c ON c.biodata_id=b.biodata_id 
			WHERE a.insentif_id={$id} 
			AND ( c.nama LIKE '%{$_GET['key']}%' OR b.nik ='{$_GET['key']}' )
			ORDER BY b.nik 
		";
	}else{
		$query = "
			SELECT * FROM pr_insentif_karyawan a
			INNER JOIN karyawan b ON a.karyawan_id=b.karyawan_id 
			WHERE a.insentif_id={$id} ORDER BY b.nik 
		";
	}

	$pr_insentif = my_get_data_by_id('pr_insentif','insentif_id',$id);
	
	$result = my_query($query );
	$row = array(); 
	$i = 0;  
	while($ey = my_fetch_array($result)){
		$i++;
		$karyawan = loaddata_karyawan($ey['karyawan_id']); 
		$jabatan = loaddata_jabatan($karyawan['jabatan_id']); 
		$pot=get_tatib_pot_insentif($pr_insentif['tanggal'] , $ey['karyawan_id']  );
		if((int) $pot <>0 ){
			$pot.=' %' ;
		}
 		$row[] = array(
			'#'=>position_text_align ($i, 'center'), 
			'nik'=>  $karyawan['nik'] ,   
			'nama'=>  $karyawan['nama_gelar'] ,   
			'nipar'=> $ey['nipar_a']  ,   
			'nh'=> $ey['nipar_h']  ,   
			'pot'=> position_text_align ($pot, 'right'), 
			'insentif'=> position_text_align (rp_format($ey['nominal']),'right')  ,   
		);
	}
	$datas = table_rows_excel($row); 
	return table_builder_excel($header , $datas , 15 ,false ); 
}

function print_plain($id){

	if(isset($_GET['key'])){
		$query = "
			SELECT * FROM pr_insentif_karyawan a
			INNER JOIN karyawan b ON a.karyawan_id=b.karyawan_id 
			INNER JOIN biodata c ON c.biodata_id=b.biodata_id 
			WHERE a.insentif_id={$id} 
			AND ( c.nama LIKE '%{$_GET['key']}%' OR b.nik ='{$_GET['key']}' )
			ORDER BY b.nik 
		";
	}else{
		$query = "
			SELECT * FROM pr_insentif_karyawan a
			INNER JOIN karyawan b ON a.karyawan_id=b.karyawan_id 
			WHERE a.insentif_id={$id} ORDER BY b.nik 
		";
	}


	$result = my_query($query ); 
	$pr_insentif = my_get_data_by_id('pr_insentif','insentif_id',$id);
	$datas = array();  
	$datas[] = array(
		 'k1'=>array("NO" ,5 ,STR_PAD_RIGHT),
		 'k2'=>array("NIK" ,10,STR_PAD_RIGHT),
		 'k3'=>array("Nama" ,30,STR_PAD_RIGHT),
		 'k4'=>array("Nipar" ,10,STR_PAD_RIGHT),  
		 'k5'=>array("N.H" ,10,STR_PAD_RIGHT),  
		 'k6'=>array("Pot. Tatib" ,10,STR_PAD_LEFT),  
		 'k7'=>array("Insentif" ,25,STR_PAD_LEFT),  
	); 
	$datas[] = array(
		 'k1'=>array(" " ,5 ,STR_PAD_RIGHT),
		 'k2'=>array(" " ,10,STR_PAD_RIGHT),
		 'k3'=>array(" " ,30,STR_PAD_RIGHT),
		 'k4'=>array(" " ,10,STR_PAD_RIGHT),  
		 'k5'=>array(" " ,10,STR_PAD_RIGHT),  
		 'k6'=>array(" " ,10,STR_PAD_LEFT),  
		 'k7'=>array(" " ,25,STR_PAD_LEFT),  
	); 
	$i=0;
	while($ey = my_fetch_array($result)){
		$i++;
		$karyawan = loaddata_karyawan($ey['karyawan_id']); 
		$jabatan = loaddata_jabatan($karyawan['jabatan_id']); 
		$pot=get_tatib_pot_insentif($pr_insentif['tanggal'] , $ey['karyawan_id']  );
		if((int) $pot <>0 ){
			$pot.=' %' ;
		}

		$datas[] = array(		 
		 'k1'=>array( $i ,5 ,STR_PAD_RIGHT),
		 'k2'=>array( $karyawan['nik'] ,10,STR_PAD_RIGHT),
		 'k3'=>array( $karyawan['nama_gelar'] ,30,STR_PAD_RIGHT),
		 'k4'=>array( $ey['nipar_a'] ,10,STR_PAD_RIGHT),  
		 'k5'=>array( $ey['nipar_h'] ,10,STR_PAD_RIGHT),  
		 'k6'=>array( $pot,10,STR_PAD_LEFT),  
		 'k7'=>array( rp_format($ey['nominal']),25,STR_PAD_LEFT),  
		);
	}
	$view = 	str_pad("CETAK INSENTIF",100," ",STR_PAD_BOTH);
	return $view ."\n"."\n".set_txt_report($datas);
}
